home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / aminet / util / rexx / rexxmode10.lha / comint.el next >
Text File  |  1992-08-16  |  59KB  |  1,388 lines

  1. ;;; -*-Emacs-Lisp-*- General command interpreter in a window stuff
  2. ;;; Copyright Olin Shivers (1988).
  3. ;;; Please imagine a long, tedious, legalistic 5-page gnu-style copyright
  4. ;;; notice appearing here to the effect that you may use this code any
  5. ;;; way you like, as long as you don't charge money for it, remove this
  6. ;;; notice, or hold me liable for its results.
  7.  
  8. ;;; The changelog is at the end of this file.
  9.  
  10. ;;; Please send me bug reports, bug fixes, and extensions, so that I can
  11. ;;; merge them into the master source.
  12. ;;;     - Olin Shivers (shivers@cs.cmu.edu)
  13.  
  14. ;;; This hopefully generalises shell mode, lisp mode, tea mode, soar mode,...
  15. ;;; This file defines a general command-interpreter-in-a-buffer package
  16. ;;; (comint mode). The idea is that you can build specific process-in-a-buffer
  17. ;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
  18. ;;; This way, all these specific packages share a common base functionality, 
  19. ;;; and a common set of bindings, which makes them easier to use (and
  20. ;;; saves code, implementation time, etc., etc.).
  21.  
  22. ;;; Several packages are already defined using comint mode:
  23. ;;; - cmushell.el defines a shell-in-a-buffer mode.
  24. ;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
  25. ;;; Cmushell and cmulisp mode are similar to, and intended to replace,
  26. ;;; their counterparts in the standard gnu emacs release (in shell.el). 
  27. ;;; These replacements are more featureful, robust, and uniform than the 
  28. ;;; released versions. The key bindings in lisp mode are also more compatible
  29. ;;; with the bindings of Hemlock and Zwei (the Lisp Machine emacs).
  30. ;;;
  31. ;;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
  32. ;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
  33. ;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
  34. ;;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
  35. ;;;   previewers, and printers from within emacs.
  36. ;;; - background.el allows csh-like job control inside emacs.
  37. ;;; It is pretty easy to make new derived modes for other processes.
  38.  
  39. ;;; For documentation on the functionality provided by comint mode, and
  40. ;;; the hooks available for customising it, see the comments below.
  41. ;;; For further information on the standard derived modes (shell, 
  42. ;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
  43.  
  44. ;;; For hints on converting existing process modes (e.g., tex-mode,
  45. ;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
  46. ;;; instead of shell-mode, see the notes at the end of this file.
  47.  
  48. (provide 'comint)
  49. (defconst comint-version "2.03")
  50.  
  51.  
  52. ;;; Brief Command Documentation:
  53. ;;;============================================================================
  54. ;;; Comint Mode Commands: (common to all derived modes, like cmushell & cmulisp
  55. ;;; mode)
  56. ;;;
  57. ;;; m-p        comint-previous-input            Cycle backwards in input history
  58. ;;; m-n        comint-next-input                  Cycle forwards
  59. ;;; m-s     comint-previous-similar-input   Previous similar input
  60. ;;; c-m-r   comint-previous-input-matching  Search backwards in input history
  61. ;;; return  comint-send-input
  62. ;;; c-a     comint-bol                      Beginning of line; skip prompt.
  63. ;;; c-d        comint-delchar-or-maybe-eof     Delete char unless at end of buff.
  64. ;;; c-c c-u comint-kill-input                ^u
  65. ;;; c-c c-w backward-kill-word            ^w
  66. ;;; c-c c-c comint-interrupt-subjob         ^c
  67. ;;; c-c c-z comint-stop-subjob                ^z
  68. ;;; c-c c-\ comint-quit-subjob                ^\
  69. ;;; c-c c-o comint-kill-output            Delete last batch of process output
  70. ;;; c-c c-r comint-show-output            Show last batch of process output
  71. ;;;
  72. ;;; Not bound by default in comint-mode
  73. ;;; send-invisible            Read a line w/o echo, and send to proc
  74. ;;; (These are bound in shell-mode)
  75. ;;; comint-dynamic-complete        Complete filename at point.
  76. ;;; comint-dynamic-list-completions    List completions in help buffer.
  77. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  78. ;;;                    replace with expanded/completed name.
  79. ;;; comint-kill-subjob            No mercy.
  80. ;;; comint-continue-subjob        Send CONT signal to buffer's process
  81. ;;;                    group. Useful if you accidentally
  82. ;;;                    suspend your process (with C-c C-z).
  83. ;;;
  84. ;;; These used to be bound for RMS -- I prefer the input history stuff,
  85. ;;; but you might like 'em.
  86. ;;; m-P       comint-msearch-input        Search backwards for prompt
  87. ;;; m-N    comint-psearch-input        Search forwards for prompt
  88. ;;; C-cR   comint-msearch-input-matching Search backwards for prompt & string
  89.  
  90. ;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
  91. ;;; comint-load-hook is run after loading in this package.
  92.  
  93.  
  94. ;;; Buffer Local Variables:
  95. ;;;============================================================================
  96. ;;; Comint mode buffer local variables:
  97. ;;;     comint-prompt-regexp    - string       comint-bol uses to match prompt.
  98. ;;;     comint-last-input-end   - marker       For comint-kill-output command
  99. ;;;     input-ring-size         - integer      For the input history
  100. ;;;     input-ring              - ring             mechanism
  101. ;;;     input-ring-index        - marker           ...
  102. ;;;     comint-last-input-match - string           ...
  103. ;;;     comint-get-old-input    - function     Hooks for specific 
  104. ;;;     comint-input-sentinel   - function         process-in-a-buffer
  105. ;;;     comint-input-filter     - function         modes.
  106. ;;;     comint-input-send    - function
  107. ;;;     comint-eol-on-send    - boolean
  108.  
  109. (defvar comint-prompt-regexp "^"
  110.   "Regexp to recognise prompts in the inferior process.
  111. Defaults to \"^\", the null string at BOL.
  112.  
  113. Good choices:
  114.   Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
  115.   Lucid Common Lisp: \"^\\(>\\|\\(->\\)+\\) *\"
  116.   franz: \"^\\(->\\|<[0-9]*>:\\) *\"
  117.   kcl: \"^>+ *\"
  118.   shell: \"^[^#$%>]*[#$%>] *\"
  119.   T: \"^>+ *\"
  120.  
  121. This is a good thing to set in mode hooks.")
  122.  
  123. (defvar input-ring-size 30
  124.   "Size of input history ring.")
  125.  
  126. ;;; Here are the per-interpreter hooks.
  127. (defvar comint-get-old-input (function comint-get-old-input-default)
  128.   "Function that submits old text in comint mode.
  129. This function is called when return is typed while the point is in old text.
  130. It returns the text to be submitted as process input.  The default is
  131. comint-get-old-input-default, which grabs the current line, and strips off
  132. leading text matching comint-prompt-regexp")
  133.  
  134. (defvar comint-input-sentinel (function ignore)
  135.   "Called on each input submitted to comint mode process by comint-send-input.
  136. Thus it can, for instance, track cd/pushd/popd commands issued to the csh.")
  137.  
  138. (defvar comint-input-filter
  139.   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
  140.   "Predicate for filtering additions to input history.
  141. Only inputs answering true to this function are saved on the input
  142. history list. Default is to save anything that isn't all whitespace")
  143.  
  144. (defvar comint-input-sender (function comint-simple-send)
  145.   "Function to actually send to PROCESS the STRING submitted by user.
  146. Usually this is just 'comint-simple-send, but if your mode needs to 
  147. massage the input string, this is your hook. This is called from
  148. the user command comint-send-input. comint-simple-send just sends
  149. the string plus a newline.")
  150.  
  151. (defvar comint-eol-on-send 'T
  152.   "If non-nil, then jump to the end of the line before sending input to process.
  153. See COMINT-SEND-INPUT")
  154.  
  155. (defvar comint-mode-hook '()
  156.   "Called upon entry into comint-mode
  157. This is run before the process is cranked up.")
  158.  
  159. (defvar comint-exec-hook '()
  160.   "Called each time a process is exec'd by comint-exec.
  161. This is called after the process is cranked up.  It is useful for things that
  162. must be done each time a process is executed in a comint-mode buffer (e.g.,
  163. (process-kill-without-query)). In contrast, the comint-mode-hook is only
  164. executed once when the buffer is created.")
  165.  
  166. (defvar comint-mode-map nil)
  167.  
  168. (defun comint-mode ()
  169.   "Major mode for interacting with an inferior interpreter.
  170. Interpreter name is same as buffer name, sans the asterisks.
  171. Return at end of buffer sends line as input.
  172. Return not at end copies rest of line to end and sends it.
  173. Setting mode variable comint-eol-on-send means jump to the end of the line
  174. before submitting new input.
  175.  
  176. This mode is typically customised to create inferior-lisp-mode,
  177. shell-mode, etc.. This can be done by setting the hooks
  178. comint-input-sentinel, comint-input-filter, comint-input-sender and
  179. comint-get-old-input to appropriate functions, and the variable
  180. comint-prompt-regexp to the appropriate regular expression.
  181.  
  182. An input history is maintained of size input-ring-size, and
  183. can be accessed with the commands comint-next-input [\\[comint-next-input]] and 
  184. comint-previous-input [\\[comint-previous-input]]. Commands not keybound by
  185. default are send-invisible, comint-dynamic-complete, and 
  186. comint-list-dynamic-completions.
  187.  
  188. If you accidentally suspend your process, use \\[comint-continue-subjob]
  189. to continue it.
  190.  
  191. \\{comint-mode-map}
  192.  
  193. Entry to this mode runs the hooks on comint-mode-hook"
  194.   (interactive)
  195.   (let ((old-ring (and (assq 'input-ring (buffer-local-variables))
  196.                (boundp 'input-ring)
  197.                input-ring))
  198.     (old-ptyp comint-ptyp)) ; preserve across local var kill. gross.
  199. ;   (kill-all-local-variables) ; Removed 1/15/90 Olin
  200.     (setq major-mode 'comint-mode)
  201.     (setq mode-name "Comint")
  202.     (setq mode-line-process '(": %s"))
  203.     (use-local-map comint-mode-map)
  204.     (make-local-variable 'comint-last-input-end)
  205.     (setq comint-last-input-end (make-marker))
  206.     (make-local-variable 'comint-last-input-match)
  207.     (setq comint-last-input-match "")
  208.     (make-local-variable 'comint-prompt-regexp) ; Don't set; default
  209.     (make-local-variable 'input-ring-size)      ; ...to global val.
  210.     (make-local-variable 'input-ring)
  211.     (make-local-variable 'input-ring-index)
  212.     (setq input-ring-index 0)
  213.     (make-local-variable 'comint-get-old-input)
  214.     (make-local-variable 'comint-input-sentinel)
  215.     (make-local-variable 'comint-input-filter)  
  216.     (make-local-variable 'comint-input-sender)
  217.     (make-local-variable 'comint-eol-on-send)
  218.     (make-local-variable 'comint-ptyp)
  219.     (setq comint-ptyp old-ptyp)
  220.     (make-local-variable 'comint-exec-hook)
  221.     (run-hooks 'comint-mode-hook)
  222.     ;Do this after the hook so the user can mung INPUT-RING-SIZE w/his hook.
  223.     ;The test is so we don't lose history if we run comint-mode twice in
  224.     ;a buffer.
  225.     (setq input-ring (if (ring-p old-ring) old-ring
  226.              (make-ring input-ring-size)))))
  227.  
  228. ;;; The old-ptyp stuff above is because we have to preserve the value of
  229. ;;; comint-ptyp across calls to comint-mode, in spite of the
  230. ;;; kill-all-local-variables that it does. Blech. Hopefully, this will all
  231. ;;; go away when a later release fixes the signalling bug.
  232. ;;; (Later: I removed the kill-all-local-variables, but have left this
  233. ;;; other code in place just in case I reverse myself.)
  234.  
  235. (if comint-mode-map
  236.     nil
  237.   (setq comint-mode-map (make-sparse-keymap))
  238.   (define-key comint-mode-map "\ep" 'comint-previous-input)
  239.   (define-key comint-mode-map "\en" 'comint-next-input)
  240.   (define-key comint-mode-map "\es" 'comint-previous-similar-input)
  241.   (define-key comint-mode-map "\C-m" 'comint-send-input)
  242.   (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
  243.   (define-key comint-mode-map "\C-a" 'comint-bol)
  244.   (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
  245.   (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
  246.   (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
  247.   (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
  248.   (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
  249.   (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
  250.   (define-key comint-mode-map "\C-\M-r"  'comint-previous-input-matching)
  251.   (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
  252.   ;;; prompt-search commands commented out 3/90 -Olin
  253. ; (define-key comint-mode-map "\eP" 'comint-msearch-input)
  254. ; (define-key comint-mode-map "\eN" 'comint-psearch-input)
  255. ; (define-key comint-mode-map "\C-cR" 'comint-msearch-input-matching)
  256.   )
  257.  
  258.  
  259. ;;; This function is used to make a full copy of the comint mode map,
  260. ;;; so that client modes won't interfere with each other. This function
  261. ;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
  262. (defun full-copy-sparse-keymap (km)
  263.   "Recursively copy the sparse keymap KM"
  264.   (cond ((consp km)
  265.      (cons (full-copy-sparse-keymap (car km))
  266.            (full-copy-sparse-keymap (cdr km))))
  267.     (t km)))
  268.  
  269. (defun comint-check-proc (buffer)
  270.   "True if there is a process associated w/buffer BUFFER, and
  271. it is alive (status RUN or STOP). BUFFER can be either a buffer or the
  272. name of one"
  273.   (let ((proc (get-buffer-process buffer)))
  274.     (and proc (memq (process-status proc) '(run stop)))))
  275.  
  276. ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
  277. ;;; for the second argument (program).
  278. (defun make-comint (name program &optional startfile &rest switches)
  279.   (let ((buffer (get-buffer-create (concat "*" name "*"))))
  280.     ;; If no process, or nuked process, crank up a new one and put buffer in
  281.     ;; comint mode. Otherwise, leave buffer and existing process alone.
  282.     (cond ((not (comint-check-proc buffer))
  283.        (save-excursion
  284.          (set-buffer buffer)
  285.          (comint-mode)) ; Install local vars, mode, keymap, ...
  286.        (comint-exec buffer name program startfile switches)))
  287.     buffer))
  288.  
  289. (defvar comint-ptyp t
  290.   "True if communications via pty; false if by pipe. Buffer local.
  291. This is to work around a bug in emacs process signalling.")
  292.  
  293. (defun comint-exec (buffer name command startfile switches)
  294.   "Fires up a process in buffer for comint modes.
  295. Blasts any old process running in the buffer. Doesn't set the buffer mode.
  296. You can use this to cheaply run a series of processes in the same comint
  297. buffer. The hook comint-exec-hook is run after each exec."
  298.   (save-excursion
  299.     (set-buffer buffer)
  300.     (let ((proc (get-buffer-process buffer)))    ; Blast any old process.
  301.       (if proc (delete-process proc)))
  302.     ;; Crank up a new process
  303.     (let ((proc (comint-exec-1 name buffer command switches)))
  304.       (make-local-variable 'comint-ptyp)
  305.       (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
  306.       ;; Jump to the end, and set the process mark.
  307.       (goto-char (point-max))
  308.       (set-marker (process-mark proc) (point))
  309.       ;; Feed it the startfile.
  310.       (cond (startfile
  311.          ;;This is guaranteed to wait long enough
  312.          ;;but has bad results if the comint does not prompt at all
  313.          ;;         (while (= size (buffer-size))
  314.          ;;           (sleep-for 1))
  315.          ;;I hope 1 second is enough!
  316.          (sleep-for 1)
  317.          (goto-char (point-max))
  318.          (insert-file-contents startfile)
  319.          (setq startfile (buffer-substring (point) (point-max)))
  320.          (delete-region (point) (point-max))
  321.          (comint-send-string proc startfile)))
  322.     (run-hooks 'comint-exec-hook)
  323.     buffer)))
  324.  
  325. ;;; This auxiliary function cranks up the process for comint-exec in
  326. ;;; the appropriate environment. It is twice as long as it should be
  327. ;;; because emacs has two distinct mechanisms for manipulating the
  328. ;;; process environment, selected at compile time with the
  329. ;;; MAINTAIN-ENVIRONMENT #define. In one case, process-environment
  330. ;;; is bound; in the other it isn't.
  331.  
  332. (defun comint-exec-1 (name buffer command switches)
  333.   (if (boundp 'process-environment) ; Not a completely reliable test.
  334.       (let ((process-environment
  335.          (comint-update-env process-environment
  336.                 (list (format "TERMCAP=emacs:co#%d:tc=unknown"
  337.                           (screen-width))
  338.                       "TERM=emacs"
  339.                       "EMACS=t"))))
  340.     (apply 'start-process name buffer command switches))
  341.  
  342.       (let ((tcapv (getenv "TERMCAP"))
  343.         (termv (getenv "TERM"))
  344.         (emv   (getenv "EMACS")))
  345.     (unwind-protect
  346.          (progn (setenv "TERMCAP" (format "emacs:co#%d:tc=unknown"
  347.                           (screen-width)))
  348.             (setenv "TERM" "emacs")
  349.             (setenv "EMACS" "t")
  350.             (apply 'start-process name buffer command switches))
  351.       (setenv "TERMCAP" tcapv)
  352.       (setenv "TERM"    termv)
  353.       (setenv "EMACS"   emv)))))
  354.          
  355.  
  356.  
  357. ;; This is just (append new old-env) that compresses out shadowed entries.
  358. ;; It's also pretty ugly, mostly due to elisp's horrible iteration structures.
  359. (defun comint-update-env (old-env new)
  360.   (let ((ans (reverse new))
  361.     (vars (mapcar (function (lambda (vv)
  362.             (and (string-match "^[^=]*=" vv)
  363.                  (substring vv 0 (match-end 0)))))
  364.               new)))
  365.     (while old-env
  366.       (let* ((vv (car old-env)) ; vv is var=value
  367.          (var (and (string-match "^[^=]*=" vv)
  368.                (substring vv 0 (match-end 0)))))
  369.     (setq old-env (cdr old-env))
  370.     (cond ((not (and var (comint-mem var vars)))
  371.            (if var (setq var (cons var vars)))
  372.            (setq ans (cons vv ans))))))
  373.     (nreverse ans)))
  374.  
  375. ;;; This should be in emacs, but it isn't.
  376. (defun comint-mem (item list &optional elt=)
  377.   "Test to see if ITEM is equal to an item in LIST.
  378. Option comparison function ELT= defaults to equal."
  379.   (let ((elt= (or elt= (function equal)))
  380.     (done nil))
  381.     (while (and list (not done))
  382.       (if (funcall elt= item (car list))
  383.       (setq done list)
  384.       (setq list (cdr list))))
  385.     done))
  386.  
  387.  
  388. ;;; Ring Code
  389. ;;;============================================================================
  390. ;;; This code defines a ring data structure. A ring is a 
  391. ;;;     (hd-index tl-index . vector) 
  392. ;;; list. You can insert to, remove from, and rotate a ring. When the ring
  393. ;;; fills up, insertions cause the oldest elts to be quietly dropped.
  394. ;;;
  395. ;;; HEAD = index of the newest item on the ring.
  396. ;;; TAIL = index of the oldest item on the ring.
  397. ;;;
  398. ;;; These functions are used by the input history mechanism, but they can
  399. ;;; be used for other purposes as well.
  400.  
  401. (defun ring-p (x) 
  402.   "T if X is a ring; NIL otherwise."
  403.   (and (consp x) (integerp (car x))
  404.        (consp (cdr x)) (integerp (car (cdr x)))
  405.        (vectorp (cdr (cdr x)))))
  406.  
  407. (defun make-ring (size)
  408.   "Make a ring that can contain SIZE elts"
  409.   (cons 1 (cons 0 (make-vector (+ size 1) nil))))
  410.  
  411. (defun ring-plus1 (index veclen)
  412.   "INDEX+1, with wraparound"
  413.   (let ((new-index (+ index 1)))
  414.     (if (= new-index veclen) 0 new-index)))
  415.  
  416. (defun ring-minus1 (index veclen)
  417.   "INDEX-1, with wraparound"
  418.   (- (if (= 0 index) veclen index) 1))
  419.  
  420. (defun ring-length (ring)
  421.   "Number of elts in the ring."
  422.   (let ((hd (car ring)) (tl (car (cdr ring)))  (siz (length (cdr (cdr ring)))))
  423.     (let ((len (if (<= hd tl) (+ 1 (- tl hd)) (+ 1 tl (- siz hd)))))
  424.       (if (= len siz) 0 len))))
  425.  
  426. (defun ring-empty-p (ring)
  427.   (= 0 (ring-length ring)))
  428.  
  429. (defun ring-insert (ring item)
  430.   "Insert a new item onto the ring. If the ring is full, dump the oldest
  431. item to make room."       
  432.   (let* ((vec (cdr (cdr ring)))  (len (length vec))
  433.      (new-hd (ring-minus1 (car ring) len)))
  434.       (setcar ring new-hd)
  435.       (aset vec new-hd item)
  436.       (if (ring-empty-p ring) ;overflow -- dump one off the tail.
  437.       (setcar (cdr ring) (ring-minus1 (car (cdr ring)) len)))))
  438.  
  439. (defun ring-remove (ring)
  440.   "Remove the oldest item retained on the ring."
  441.   (if (ring-empty-p ring) (error "Ring empty")
  442.       (let ((tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  443.     (set-car (cdr ring) (ring-minus1 tl (length vec)))
  444.     (aref vec tl))))
  445.  
  446. ;;; This isn't actually used in this package. I just threw it in in case
  447. ;;; someone else wanted it. If you want rotating-ring behavior on your history
  448. ;;; retrieval (analagous to kill ring behavior), this function is what you
  449. ;;; need. I should write the yank-input and yank-pop-input-or-kill to go with
  450. ;;; this, and not bind it to a key by default, so it would be available to
  451. ;;; people who want to bind it to a key. But who would want it? Blech.
  452. (defun ring-rotate (ring n)
  453.   (if (not (= n 0))
  454.       (if (ring-empty-p ring) ;Is this the right error check?
  455.       (error "ring empty")
  456.       (let ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  457.         (let ((len (length vec)))
  458.           (while (> n 0)
  459.         (setq tl (ring-plus1 tl len))
  460.         (aset ring tl (aref ring hd))
  461.         (setq hd (ring-plus1 hd len))
  462.         (setq n (- n 1)))
  463.           (while (< n 0)
  464.         (setq hd (ring-minus1 hd len))
  465.         (aset vec hd (aref vec tl))
  466.         (setq tl (ring-minus1 tl len))
  467.         (setq n (- n 1))))
  468.         (set-car ring hd)
  469.         (set-car (cdr ring) tl)))))
  470.  
  471. (defun comint-mod (n m)
  472.   "Returns N mod M. M is positive. Answer is guaranteed to be non-negative, 
  473. and less than m."
  474.   (let ((n (% n m)))
  475.     (if (>= n 0) n
  476.     (+ n
  477.        (if (>= m 0) m (- m)))))) ; (abs m)
  478.  
  479. (defun ring-ref (ring index)
  480.   (let ((numelts (ring-length ring)))
  481.     (if (= numelts 0) (error "indexed empty ring")
  482.     (let* ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring)))
  483.            (index (comint-mod index numelts))
  484.            (vec-index (comint-mod (+ index hd) 
  485.                       (length vec))))
  486.       (aref vec vec-index)))))
  487.  
  488.  
  489. ;;; Input history retrieval commands
  490. ;;; M-p -- previous input    M-n -- next input
  491. ;;; M-C-r -- previous input matching
  492. ;;; ===========================================================================
  493.  
  494. (defun comint-previous-input (arg)
  495.   "Cycle backwards through input history."
  496.   (interactive "*p")
  497.   (let ((len (ring-length input-ring)))
  498.     (cond ((<= len 0)
  499.        (message "Empty input ring")
  500.        (ding))
  501.       ((not (comint-after-pmark-p))
  502.        (message "Not after process mark")
  503.        (ding))
  504.       (t
  505.        (cond ((eq last-command 'comint-previous-input)
  506.           (delete-region (mark) (point)))
  507.          ((eq last-command 'comint-previous-similar-input)
  508.           (delete-region 
  509.            (process-mark (get-buffer-process (current-buffer)))
  510.            (point)))
  511.          (t                          
  512.           (setq input-ring-index
  513.             (if (> arg 0) -1
  514.                 (if (< arg 0) 1 0)))
  515.           (push-mark (point))))
  516.        (setq input-ring-index (comint-mod (+ input-ring-index arg) len))
  517.        (message "%d" (1+ input-ring-index))
  518.        (insert (ring-ref input-ring input-ring-index))
  519.        (setq this-command 'comint-previous-input)))))
  520.      
  521. (defun comint-next-input (arg)
  522.   "Cycle forwards through input history."
  523.   (interactive "*p")
  524.   (comint-previous-input (- arg)))
  525.  
  526. (defvar comint-last-input-match ""
  527.   "Last string searched for by comint input history search, for defaulting.
  528. Buffer local variable.") 
  529.  
  530. (defun comint-previous-input-matching (str)
  531.   "Searches backwards through input history for substring match."
  532.   (interactive (let* ((last-command last-command) ; preserve around r-f-m
  533.               (s (read-from-minibuffer 
  534.              (format "Command substring (default %s): "
  535.                  comint-last-input-match))))
  536.          (list (if (string= s "") comint-last-input-match s))))
  537. ; (interactive "sCommand substring: ")
  538.   (setq comint-last-input-match str) ; update default
  539.   (if (not (eq last-command 'comint-previous-input))
  540.       (setq input-ring-index -1))
  541.   (let ((str (regexp-quote str))
  542.         (len (ring-length input-ring))
  543.     (n (+ input-ring-index 1)))
  544.     (while (and (< n len) (not (string-match str (ring-ref input-ring n))))
  545.       (setq n (+ n 1)))
  546.     (cond ((< n len)
  547.        (comint-previous-input (- n input-ring-index)))
  548.       (t (if (eq last-command 'comint-previous-input) 
  549.          (setq this-command 'comint-previous-input))
  550.          (message "Not found.")
  551.          (ding)))))
  552.  
  553.  
  554. ;;; These next three commands are alternatives to the input history commands
  555. ;;; -- comint-next-input, comint-previous-input and
  556. ;;; comint-previous-input-matching. They search through the process buffer
  557. ;;; text looking for occurrences of the prompt.  Bound to M-P, M-N, and C-c R
  558. ;;; (uppercase P, N, and R) for now. Try'em out. Go with what you like...
  559.  
  560. ;;; comint-msearch-input-matching prompts for a string, not a regexp.
  561. ;;; This could be considered to be the wrong thing. I decided to keep it
  562. ;;; simple, and not make the user worry about regexps. This, of course,
  563. ;;; limits functionality.
  564.  
  565. ;;; These commands were deemed non-winning and have been commented out.
  566. ;;; Feel free to re-enable them if you like. -Olin 3/91
  567.  
  568. ;(defun comint-psearch-input ()
  569. ;  "Search forwards for next occurrence of prompt and skip to end of line.
  570. ;\(prompt is anything matching regexp comint-prompt-regexp)"
  571. ;  (interactive)
  572. ;  (if (re-search-forward comint-prompt-regexp (point-max) t)
  573. ;      (end-of-line)
  574. ;      (error "No occurrence of prompt found")))
  575. ;
  576. ;(defun comint-msearch-input ()
  577. ;  "Search backwards for previous occurrence of prompt and skip to end of line.
  578. ;Search starts from beginning of current line."
  579. ;  (interactive)
  580. ;  (let ((p (save-excursion
  581. ;         (beginning-of-line)
  582. ;         (cond ((re-search-backward comint-prompt-regexp (point-min) t)
  583. ;            (end-of-line)
  584. ;            (point))
  585. ;           (t nil)))))
  586. ;    (if p (goto-char p)
  587. ;    (error "No occurrence of prompt found"))))
  588. ;
  589. ;(defun comint-msearch-input-matching (str)
  590. ;  "Search backwards for occurrence of prompt followed by STRING.
  591. ;STRING is prompted for, and is NOT a regular expression."
  592. ;  (interactive (let ((s (read-from-minibuffer 
  593. ;             (format "Command (default %s): "
  594. ;                 comint-last-input-match))))
  595. ;         (list (if (string= s "") comint-last-input-match s))))
  596. ;; (interactive "sCommand: ")
  597. ;  (setq comint-last-input-match str) ; update default
  598. ;  (let* ((r (concat comint-prompt-regexp (regexp-quote str)))
  599. ;     (p (save-excursion
  600. ;          (beginning-of-line)
  601. ;          (cond ((re-search-backward r (point-min) t)
  602. ;             (end-of-line)
  603. ;             (point))
  604. ;            (t nil)))))
  605. ;    (if p (goto-char p)
  606. ;    (error "No match"))))
  607.  
  608. ;;;
  609. ;;; Similar input -- contributed by ccm and highly winning.
  610. ;;;
  611. ;;; Reenter input, removing back to the last insert point if it exists. 
  612. ;;;
  613. (defvar comint-last-similar-string "" 
  614.   "The string last used in a similar string search.")
  615. (defun comint-previous-similar-input (arg)
  616.   "Reenters the last input that matches the string typed so far.  If repeated 
  617. successively older inputs are reentered.  If arg is 1, it will go back
  618. in the history, if -1 it will go forward."
  619.   (interactive "p")
  620.   (if (not (comint-after-pmark-p))
  621.       (error "Not after process mark"))
  622.   (if (not (eq last-command 'comint-previous-similar-input))
  623.       (setq input-ring-index -1
  624.         comint-last-similar-string 
  625.         (buffer-substring 
  626.          (process-mark (get-buffer-process (current-buffer)))
  627.          (point))))
  628.   (let* ((size (length comint-last-similar-string))
  629.      (len (ring-length input-ring))
  630.      (n (+ input-ring-index arg))
  631.      entry)
  632.     (while (and (< n len) 
  633.         (or (< (length (setq entry (ring-ref input-ring n))) size)
  634.             (not (equal comint-last-similar-string 
  635.                 (substring entry 0 size)))))
  636.       (setq n (+ n arg)))
  637.     (cond ((< n len)
  638.        (setq input-ring-index n)
  639.        (if (eq last-command 'comint-previous-similar-input)
  640.            (delete-region (mark) (point)) ; repeat
  641.            (push-mark (point)))          ; 1st time
  642.        (insert (substring entry size)))
  643.       (t (message "Not found.") (ding) (sit-for 1)))
  644.     (message "%d" (1+ input-ring-index))))
  645.  
  646.  
  647. (defun comint-send-input () 
  648.   "Send input to process.  After the process output mark, sends all text
  649. from the process mark to point as input to the process.  Before the process
  650. output mark, calls value of variable comint-get-old-input to retrieve old
  651. input, copies it to the process mark, and sends it.  A terminal newline is
  652. also inserted into the buffer and sent to the process.  In either case, value
  653. of variable comint-input-sentinel is called on the input before sending it.
  654. The input is entered into the input history ring, if the value of variable
  655. comint-input-filter returns non-nil when called on the input.
  656.  
  657. If variable comint-eol-on-send is non-nil, then point is moved to the end of
  658. line before sending the input.
  659.  
  660. comint-get-old-input, comint-input-sentinel, and comint-input-filter are chosen
  661. according to the command interpreter running in the buffer. E.g.,
  662. If the interpreter is the csh,
  663.     comint-get-old-input is the default: take the current line, discard any
  664.         initial string matching regexp comint-prompt-regexp.
  665.     comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\" 
  666.         commands. When it sees one, it cd's the buffer.
  667.     comint-input-filter is the default: returns T if the input isn't all white
  668.     space.
  669.  
  670. If the comint is Lucid Common Lisp, 
  671.     comint-get-old-input snarfs the sexp ending at point.
  672.     comint-input-sentinel does nothing.
  673.     comint-input-filter returns NIL if the input matches input-filter-regexp,
  674.         which matches (1) all whitespace (2) :a, :c, etc.
  675.  
  676. Similarly for Soar, Scheme, etc.."
  677.   (interactive)
  678.   ;; Note that the input string does not include its terminal newline.
  679.   (let ((proc (get-buffer-process (current-buffer))))
  680.     (if (not proc) (error "Current buffer has no process")
  681.     (let* ((pmark (process-mark proc))
  682.            (pmark-val (marker-position pmark))
  683.            (input (if (>= (point) pmark-val)
  684.               (progn (if comint-eol-on-send (end-of-line))
  685.                  (buffer-substring pmark (point)))
  686.               (let ((copy (funcall comint-get-old-input)))
  687.                 (goto-char pmark)
  688.                 (insert copy)
  689.                 copy))))
  690.       (insert ?\n)
  691.       (if (funcall comint-input-filter input) (ring-insert input-ring input))
  692.       (funcall comint-input-sentinel input)
  693.       (funcall comint-input-sender proc input)
  694.       (set-marker (process-mark proc) (point))
  695.       (set-marker comint-last-input-end (point))))))
  696.  
  697. (defun comint-get-old-input-default ()
  698.   "Default for comint-get-old-input: take the current line, and discard
  699. any initial text matching comint-prompt-regexp."
  700.   (save-excursion
  701.     (beginning-of-line)
  702.     (comint-skip-prompt)
  703.     (let ((beg (point)))
  704.       (end-of-line)
  705.       (buffer-substring beg (point)))))
  706.  
  707. (defun comint-skip-prompt ()
  708.   "Skip past the text matching regexp comint-prompt-regexp. 
  709. If this takes us past the end of the current line, don't skip at all."
  710.   (let ((eol (save-excursion (end-of-line) (point))))
  711.     (if (and (looking-at comint-prompt-regexp)
  712.          (<= (match-end 0) eol))
  713.     (goto-char (match-end 0)))))
  714.  
  715.  
  716. (defun comint-after-pmark-p ()
  717.   "Is point after the process output marker?"
  718.   ;; Since output could come into the buffer after we looked at the point
  719.   ;; but before we looked at the process marker's value, we explicitly 
  720.   ;; serialise. This is just because I don't know whether or not emacs
  721.   ;; services input during execution of lisp commands.
  722.   (let ((proc-pos (marker-position
  723.            (process-mark (get-buffer-process (current-buffer))))))
  724.     (<= proc-pos (point))))
  725.  
  726. (defun comint-simple-send (proc string)
  727.   "Default function for sending to PROC input STRING.
  728. This just sends STRING plus a newline. To override this,
  729. set the hook COMINT-INPUT-SENDER."
  730.   (comint-send-string proc string)
  731.   (comint-send-string proc "\n"))
  732.  
  733. (defun comint-bol (arg)
  734.   "Goes to the beginning of line, then skips past the prompt, if any.
  735. If a prefix argument is given (\\[universal-argument]), then no prompt skip 
  736. -- go straight to column 0.
  737.  
  738. The prompt skip is done by skipping text matching the regular expression
  739. comint-prompt-regexp, a buffer local variable.
  740.  
  741. If you don't like this command, reset c-a to beginning-of-line 
  742. in your hook, comint-mode-hook."
  743.   (interactive "P")
  744.   (beginning-of-line)
  745.   (if (null arg) (comint-skip-prompt)))
  746.  
  747. ;;; These two functions are for entering text you don't want echoed or
  748. ;;; saved -- typically passwords to ftp, telnet, or somesuch.
  749. ;;; Just enter m-x send-invisible and type in your line.
  750.  
  751. (defun comint-read-noecho (prompt &optional stars)
  752.   "Prompt the user with argument PROMPT. Read a single line of text
  753. without echoing, and return it. Note that the keystrokes comprising
  754. the text can still be recovered (temporarily) with \\[view-lossage]. This
  755. may be a security bug for some applications. Optional argument STARS
  756. causes input to be echoed with '*' characters on the prompt line."
  757.   (let ((echo-keystrokes 0)
  758.     (cursor-in-echo-area t)
  759.     (answ "")
  760.     tem)
  761.     (if (not (stringp prompt)) (setq prompt ""))
  762.     (message prompt)
  763.     (while (not(or  (= (setq tem (read-char)) ?\^m)
  764.             (= tem ?\n)))
  765.       (setq answ (concat answ (char-to-string tem)))
  766.       (if stars (setq prompt (concat prompt "*")))
  767.       (message prompt))
  768.     (message "")
  769.     answ))
  770.  
  771.  
  772. (defun send-invisible (str)
  773.   "Read a string without echoing, and send it to the process running
  774. in the current buffer. A new-line is additionally sent. String is not 
  775. saved on comint input history list.
  776. Security bug: your string can still be temporarily recovered with
  777. \\[view-lossage]."
  778. ; (interactive (list (comint-read-noecho "Enter non-echoed text")))
  779.   (interactive "P") ; Defeat snooping via C-x esc
  780.   (let ((proc (get-buffer-process (current-buffer))))
  781.     (if (not proc) (error "Current buffer has no process")
  782.     (comint-send-string proc
  783.                 (if (stringp str) str
  784.                 (comint-read-noecho "Non-echoed text: " t)))
  785.     (comint-send-string proc "\n"))))
  786.  
  787.  
  788. ;;; Low-level process communication
  789.  
  790. (defvar comint-input-chunk-size 512
  791.   "*Long inputs send to comint processes are broken up into chunks of this size.
  792. If your process is choking on big inputs, try lowering the value.")
  793.  
  794. (defun comint-send-string (proc str)
  795.   "Send PROCESS the contents of STRING as input.
  796. This is equivalent to process-send-string, except that long input strings
  797. are broken up into chunks of size comint-input-chunk-size. Processes
  798. are given a chance to output between chunks. This can help prevent processes
  799. from hanging when you send them long inputs on some OS's."
  800.   (let* ((len (length str))
  801.      (i (min len comint-input-chunk-size)))
  802.     (process-send-string proc (substring str 0 i))
  803.     (while (< i len)
  804.       (let ((next-i (+ i comint-input-chunk-size)))
  805.     (accept-process-output)
  806.     (process-send-string proc (substring str i (min len next-i)))
  807.     (setq i next-i)))))
  808.  
  809. (defun comint-send-region (proc start end)
  810.   "Sends to PROC the region delimited by START and END.
  811. This is a replacement for process-send-region that tries to keep
  812. your process from hanging on long inputs. See comint-send-string."
  813.   (comint-send-string proc (buffer-substring start end)))
  814.  
  815.  
  816. ;;; Random input hackage
  817.  
  818. (defun comint-kill-output ()
  819.   "Kill all output from interpreter since last input."
  820.   (interactive)
  821.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  822.     (kill-region comint-last-input-end pmark)
  823.     (goto-char pmark)    
  824.     (insert "*** output flushed ***\n")
  825.     (set-marker pmark (point))))
  826.  
  827. (defun comint-show-output ()
  828.   "Display start of this batch of interpreter output at top of window.
  829. Also put cursor there."
  830.   (interactive)
  831.   (goto-char comint-last-input-end)
  832.   (backward-char)
  833.   (beginning-of-line)
  834.   (set-window-start (selected-window) (point))
  835.   (end-of-line))
  836.  
  837. (defun comint-interrupt-subjob ()
  838.   "Interrupt the current subjob."
  839.   (interactive)
  840.   (interrupt-process nil comint-ptyp))
  841.  
  842. (defun comint-kill-subjob ()
  843.   "Send kill signal to the current subjob."
  844.   (interactive)
  845.   (kill-process nil comint-ptyp))
  846.  
  847. (defun comint-quit-subjob ()
  848.   "Send quit signal to the current subjob."
  849.   (interactive)
  850.   (quit-process nil comint-ptyp))
  851.  
  852. (defun comint-stop-subjob ()
  853.   "Stop the current subjob.
  854. WARNING: if there is no current subjob, you can end up suspending
  855. the top-level process running in the buffer. If you accidentally do
  856. this, use \\[comint-continue-subjob] to resume the process. (This
  857. is not a problem with most shells, since they ignore this signal.)"
  858.   (interactive)
  859.   (stop-process nil comint-ptyp))
  860.  
  861. (defun comint-continue-subjob ()
  862.   "Send CONT signal to process buffer's process group.
  863. Useful if you accidentally suspend the top-level process."
  864.   (interactive)
  865.   (continue-process nil comint-ptyp))
  866.  
  867. (defun comint-kill-input ()
  868.   "Kill all text from last stuff output by interpreter to point."
  869.   (interactive)
  870.   (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
  871.      (p-pos (marker-position pmark)))
  872.     (if (> (point) p-pos)
  873.     (kill-region pmark (point)))))
  874.  
  875. (defun comint-delchar-or-maybe-eof (arg)
  876.   "Delete ARG characters forward, or send an EOF to process if at end of buffer."
  877.   (interactive "p")
  878.   (if (eobp)
  879.       (process-send-eof)
  880.       (delete-char arg)))
  881.  
  882.  
  883.  
  884.  
  885. ;;; Support for source-file processing commands.
  886. ;;;============================================================================
  887. ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
  888. ;;; commands that process files of source text (e.g. loading or compiling
  889. ;;; files). So the corresponding process-in-a-buffer modes have commands
  890. ;;; for doing this (e.g., lisp-load-file). The functions below are useful
  891. ;;; for defining these commands.
  892. ;;;
  893. ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
  894. ;;; and Soar, in that they don't know anything about file extensions.
  895. ;;; So the compile/load interface gets the wrong default occasionally.
  896. ;;; The load-file/compile-file default mechanism could be smarter -- it
  897. ;;; doesn't know about the relationship between filename extensions and
  898. ;;; whether the file is source or executable. If you compile foo.lisp
  899. ;;; with compile-file, then the next load-file should use foo.bin for
  900. ;;; the default, not foo.lisp. This is tricky to do right, particularly
  901. ;;; because the extension for executable files varies so much (.o, .bin,
  902. ;;; .lbin, .mo, .vo, .ao, ...).
  903.  
  904.  
  905. ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
  906. ;;; commands.
  907. ;;;
  908. ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
  909. ;;; want to save the buffer before issuing any process requests to the command
  910. ;;; interpreter.
  911. ;;;
  912. ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
  913. ;;; for the file to process.
  914.  
  915. ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
  916. ;;;============================================================================
  917. ;;; This function computes the defaults for the load-file and compile-file
  918. ;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
  919. ;;; 
  920. ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
  921. ;;; source-file processing command. NIL if there hasn't been one yet.
  922. ;;; - SOURCE-MODES is a list used to determine what buffers contain source
  923. ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
  924. ;;; Typically, (lisp-mode) or (scheme-mode).
  925. ;;; 
  926. ;;; If the command is given while the cursor is inside a string, *and*
  927. ;;; the string is an existing filename, *and* the filename is not a directory,
  928. ;;; then the string is taken as default. This allows you to just position
  929. ;;; your cursor over a string that's a filename and have it taken as default.
  930. ;;;
  931. ;;; If the command is given in a file buffer whose major mode is in
  932. ;;; SOURCE-MODES, then the the filename is the default file, and the
  933. ;;; file's directory is the default directory.
  934. ;;; 
  935. ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
  936. ;;; then the default directory & file are what was used in the last source-file
  937. ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
  938. ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
  939. ;;; is the cwd, with no default file. (\"no default file\" = nil)
  940. ;;; 
  941. ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
  942. ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
  943. ;;; for Soar programs, etc.
  944. ;;; 
  945. ;;; The function returns a pair: (default-directory . default-file).
  946.  
  947. (defun comint-source-default (previous-dir/file source-modes)
  948.   (cond ((and buffer-file-name (memq major-mode source-modes))
  949.      (cons (file-name-directory    buffer-file-name)
  950.            (file-name-nondirectory buffer-file-name)))
  951.     (previous-dir/file)
  952.     (t
  953.      (cons default-directory nil))))
  954.  
  955.  
  956. ;;; (COMINT-CHECK-SOURCE fname)
  957. ;;;============================================================================
  958. ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
  959. ;;; process-in-a-buffer modes), this function can be called on the filename.
  960. ;;; If the file is loaded into a buffer, and the buffer is modified, the user
  961. ;;; is queried to see if he wants to save the buffer before proceeding with
  962. ;;; the load or compile.
  963.  
  964. (defun comint-check-source (fname)
  965.   (let ((buff (get-file-buffer fname)))
  966.     (if (and buff
  967.          (buffer-modified-p buff)
  968.          (y-or-n-p (format "Save buffer %s first? "
  969.                    (buffer-name buff))))
  970.     ;; save BUFF.
  971.     (let ((old-buffer (current-buffer)))
  972.       (set-buffer buff)
  973.       (save-buffer)
  974.       (set-buffer old-buffer)))))
  975.  
  976.  
  977. ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
  978. ;;;============================================================================
  979. ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
  980. ;;; commands that process source files (like loading or compiling a file).
  981. ;;; It prompts for the filename, provides a default, if there is one,
  982. ;;; and returns the result filename.
  983. ;;; 
  984. ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
  985. ;;; 
  986. ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
  987. ;;; from the last source processing command.  SOURCE-MODES is a list of major
  988. ;;; modes used to determine what file buffers contain source files.  (These
  989. ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
  990. ;;; then the filename reader will only accept a file that exists.
  991. ;;; 
  992. ;;; A typical use:
  993. ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
  994. ;;;                                 '(lisp-mode) t))
  995.  
  996. ;;; This is pretty stupid about strings. It decides we're in a string
  997. ;;; if there's a quote on both sides of point on the current line.
  998. (defun comint-extract-string ()
  999.   "Returns string around point that starts the current line or nil." 
  1000.   (save-excursion
  1001.     (let* ((point (point))
  1002.        (bol (progn (beginning-of-line) (point)))
  1003.        (eol (progn (end-of-line) (point)))
  1004.        (start (progn (goto-char point) 
  1005.              (and (search-backward "\"" bol t) 
  1006.                   (1+ (point)))))
  1007.        (end (progn (goto-char point)
  1008.                (and (search-forward "\"" eol t)
  1009.                 (1- (point))))))
  1010.       (and start end
  1011.        (buffer-substring start end)))))
  1012.  
  1013. (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
  1014.   (let* ((def (comint-source-default prev-dir/file source-modes))
  1015.          (stringfile (comint-extract-string))
  1016.      (sfile-p (and stringfile
  1017.                (condition-case ()
  1018.                (file-exists-p stringfile)
  1019.              (error nil))
  1020.                (not (file-directory-p stringfile))))
  1021.      (defdir  (if sfile-p (file-name-directory stringfile)
  1022.                       (car def)))
  1023.      (deffile (if sfile-p (file-name-nondirectory stringfile)
  1024.                       (cdr def)))
  1025.      (ans (read-file-name (if deffile (format "%s(default %s) "
  1026.                           prompt    deffile)
  1027.                   prompt)
  1028.                   defdir
  1029.                   (concat defdir deffile)
  1030.                   mustmatch-p)))
  1031.     (list (expand-file-name (substitute-in-file-name ans)))))
  1032.  
  1033. ;;; I am somewhat divided on this string-default feature. It seems
  1034. ;;; to violate the principle-of-least-astonishment, in that it makes
  1035. ;;; the default harder to predict, so you actually have to look and see
  1036. ;;; what the default really is before choosing it. This can trip you up.
  1037. ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
  1038. ;;; on this.
  1039. ;;;     -Olin
  1040.  
  1041.  
  1042. ;;; Simple process query facility.
  1043. ;;; ===========================================================================
  1044. ;;; This function is for commands that want to send a query to the process
  1045. ;;; and show the response to the user. For example, a command to get the
  1046. ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
  1047. ;;; to an inferior Common Lisp process.
  1048. ;;; 
  1049. ;;; This simple facility just sends strings to the inferior process and pops
  1050. ;;; up a window for the process buffer so you can see what the process
  1051. ;;; responds with.  We don't do anything fancy like try to intercept what the
  1052. ;;; process responds with and put it in a pop-up window or on the message
  1053. ;;; line. We just display the buffer. Low tech. Simple. Works good.
  1054.  
  1055. ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
  1056. ;;; a window for the inferior process so that its response can be seen.
  1057. (defun comint-proc-query (proc str)
  1058.   (let* ((proc-buf (process-buffer proc))
  1059.      (proc-mark (process-mark proc)))
  1060.     (display-buffer proc-buf)
  1061.     (set-buffer proc-buf) ; but it's not the selected *window*
  1062.     (let ((proc-win (get-buffer-window proc-buf))
  1063.       (proc-pt (marker-position proc-mark)))
  1064.       (comint-send-string proc str) ; send the query
  1065.       (accept-process-output proc)  ; wait for some output
  1066.       ;; Try to position the proc window so you can see the answer.
  1067.       ;; This is bogus code. If you delete the (sit-for 0), it breaks.
  1068.       ;; I don't know why. Wizards invited to improve it.
  1069.       (if (not (pos-visible-in-window-p proc-pt proc-win))
  1070.       (let ((opoint (window-point proc-win)))
  1071.         (set-window-point proc-win proc-mark) (sit-for 0)
  1072.         (if (not (pos-visible-in-window-p opoint proc-win))
  1073.         (push-mark opoint)
  1074.         (set-window-point proc-win opoint)))))))
  1075.  
  1076.  
  1077. ;;; Filename completion in a buffer
  1078. ;;; ===========================================================================
  1079. ;;; Useful completion functions, courtesy of the Ergo group.
  1080. ;;; M-<Tab> will complete the filename at the cursor as much as possible
  1081. ;;; M-? will display a list of completions in the help buffer.
  1082.  
  1083. ;;; Three commands:
  1084. ;;; comint-dynamic-complete        Complete filename at point.
  1085. ;;; comint-dynamic-list-completions    List completions in help buffer.
  1086. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  1087. ;;;                    replace with expanded/completed name.
  1088.  
  1089. ;;; These are not installed in the comint-mode keymap. But they are
  1090. ;;; available for people who want them. Shell-mode installs them:
  1091. ;;; (define-key cmushell-mode-map "\M-\t" 'comint-dynamic-complete)
  1092. ;;; (define-key cmushell-mode-map "\M-?"  'comint-dynamic-list-completions)))
  1093. ;;;
  1094. ;;; Commands like this are fine things to put in load hooks if you
  1095. ;;; want them present in specific modes. Example:
  1096. ;;; (setq cmushell-load-hook
  1097. ;;;       '((lambda () (define-key lisp-mode-map "\M-\t"
  1098. ;;;                   'comint-replace-by-expanded-filename))))
  1099. ;;;          
  1100.  
  1101.  
  1102. (defun comint-match-partial-pathname ()
  1103.   "Returns the filename at point or causes an error."
  1104.   (save-excursion
  1105.     (if (re-search-backward "[^~/A-Za-z0-9---_.$#,=]" nil 'move)
  1106.     (forward-char 1))
  1107.     ;; Anchor the search forwards.
  1108.     (if (not (looking-at "[~/A-Za-z0-9---_.$#,=]")) (error ""))
  1109.     (re-search-forward "[~/A-Za-z0-9---_.$#,=]+")
  1110.     (substitute-in-file-name
  1111.      (buffer-substring (match-beginning 0) (match-end 0)))))
  1112.  
  1113.  
  1114. (defun comint-replace-by-expanded-filename ()
  1115. "Replace the filename at point with an expanded, canonicalised, and
  1116. completed replacement.
  1117. \"Expanded\" means environment variables (e.g., $HOME) and ~'s are
  1118. replaced with the corresponding directories.  \"Canonicalised\" means ..
  1119. and \. are removed, and the filename is made absolute instead of relative.
  1120. See functions expand-file-name and substitute-in-file-name. See also
  1121. comint-dynamic-complete."
  1122.   (interactive)
  1123.   (let* ((pathname (comint-match-partial-pathname))
  1124.      (pathdir (file-name-directory pathname))
  1125.      (pathnondir (file-name-nondirectory pathname))
  1126.      (completion (file-name-completion pathnondir
  1127.                        (or pathdir default-directory))))
  1128.     (cond ((null completion)
  1129.        (message "No completions of %s." pathname)
  1130.        (ding))
  1131.       ((eql completion t)
  1132.        (message "Unique completion."))
  1133.       (t                ; this means a string was returned.
  1134.        (delete-region (match-beginning 0) (match-end 0))
  1135.        (insert (expand-file-name (concat pathdir completion)))))))
  1136.  
  1137.  
  1138. (defun comint-dynamic-complete ()
  1139.   "Dynamically complete the filename at point.
  1140. This function is similar to comint-replace-by-expanded-filename, except
  1141. that it won't change parts of the filename already entered in the buffer; 
  1142. it just adds completion characters to the end of the filename."
  1143.   (interactive)
  1144.   (let* ((pathname (comint-match-partial-pathname))
  1145.      (pathdir (file-name-directory pathname))
  1146.      (pathnondir (file-name-nondirectory pathname))
  1147.      (completion (file-name-completion  pathnondir
  1148.                        (or pathdir default-directory))))
  1149.     (cond ((null completion)
  1150.        (message "No completions of %s." pathname)
  1151.        (ding))
  1152.       ((eql completion t)
  1153.        (message "Unique completion."))
  1154.       (t                ; this means a string was returned.
  1155.        (goto-char (match-end 0))
  1156.        (insert (substring completion (length pathnondir)))))))
  1157.  
  1158. (defun comint-dynamic-list-completions ()
  1159.   "List in help buffer all possible completions of the filename at point."
  1160.   (interactive)
  1161.   (let* ((pathname (comint-match-partial-pathname))
  1162.      (pathdir (file-name-directory pathname))
  1163.      (pathnondir (file-name-nondirectory pathname))
  1164.      (completions
  1165.       (file-name-all-completions pathnondir
  1166.                      (or pathdir default-directory))))
  1167.     (cond ((null completions)
  1168.        (message "No completions of %s." pathname)
  1169.        (ding))
  1170.       (t
  1171.        (let ((conf (current-window-configuration)))
  1172.          (with-output-to-temp-buffer "*Help*"
  1173.            (display-completion-list completions))
  1174.          (sit-for 0)
  1175.          (message "Hit space to flush.")
  1176.          (let ((ch (read-char)))
  1177.            (if (= ch ?\ )
  1178.            (set-window-configuration conf)
  1179.            (setq unread-command-char ch))))))))
  1180.  
  1181. ; Ergo bindings
  1182. ; (global-set-key "\M-\t" 'comint-replace-by-expanded-filename)
  1183. ; (global-set-key "\M-?" 'comint-dynamic-list-completions)
  1184. ; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1185.  
  1186. ;;; Converting process modes to use comint mode
  1187. ;;; ===========================================================================
  1188. ;;; Several gnu packages (tex-mode, background, dbx, gdb, kermit, prolog, 
  1189. ;;; telnet are some) use the shell package as clients. Most of them would
  1190. ;;; be better off using the comint package, but they predate it. 
  1191. ;;;
  1192. ;;; Altering these packages to use comint mode should greatly
  1193. ;;; improve their functionality, and is fairly easy.
  1194. ;;; 
  1195. ;;; Renaming variables
  1196. ;;; Most of the work is renaming variables and functions. These are the common
  1197. ;;; ones:
  1198. ;;; Local variables:
  1199. ;;;     last-input-end        comint-last-input-end
  1200. ;;;    last-input-start    <unnecessary>
  1201. ;;;    shell-prompt-pattern    comint-prompt-regexp
  1202. ;;;     shell-set-directory-error-hook <no equivalent>
  1203. ;;; Miscellaneous:
  1204. ;;;    shell-set-directory    <unnecessary>
  1205. ;;;     shell-mode-map        comint-mode-map
  1206. ;;; Commands:
  1207. ;;;    shell-send-input    comint-send-input
  1208. ;;;    shell-send-eof        comint-delchar-or-maybe-eof
  1209. ;;;     kill-shell-input    comint-kill-input
  1210. ;;;    interrupt-shell-subjob    comint-interrupt-subjob
  1211. ;;;    stop-shell-subjob    comint-stop-subjob
  1212. ;;;    quit-shell-subjob    comint-quit-subjob
  1213. ;;;    kill-shell-subjob    comint-kill-subjob
  1214. ;;;    kill-output-from-shell    comint-kill-output
  1215. ;;;    show-output-from-shell    comint-show-output
  1216. ;;;    copy-last-shell-input    Use comint-previous-input/comint-next-input
  1217. ;;;
  1218. ;;; LAST-INPUT-START is no longer necessary because inputs are stored on the
  1219. ;;; input history ring. SHELL-SET-DIRECTORY is gone, its functionality taken
  1220. ;;; over by SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
  1221. ;;; Comint mode does not provide functionality equivalent to 
  1222. ;;; shell-set-directory-error-hook; it is gone.
  1223. ;;; 
  1224. ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
  1225. ;;; *not* create the comint-mode local variables in your foo-mode function.
  1226. ;;; This is not modular.  Instead, call comint-mode, and let *it* create the
  1227. ;;; necessary comint-specific local variables. Then create the
  1228. ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
  1229. ;;; be foo-mode-map, and its mode to be foo-mode.  Set the comint-mode hooks
  1230. ;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
  1231. ;;; comint-get-old-input) that need to be different from the defaults.  Call
  1232. ;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
  1233. ;;; comint-mode will take care of it. The following example, from cmushell.el,
  1234. ;;; is typical:
  1235. ;;; 
  1236. ;;; (defun shell-mode ()
  1237. ;;;   (interactive)
  1238. ;;;   (comint-mode)
  1239. ;;;   (setq comint-prompt-regexp shell-prompt-pattern)
  1240. ;;;   (setq major-mode 'shell-mode)
  1241. ;;;   (setq mode-name "Shell")
  1242. ;;;   (cond ((not shell-mode-map)
  1243. ;;;          (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
  1244. ;;;          (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1245. ;;;          (define-key shell-mode-map "\M-?"
  1246. ;;;                      'comint-dynamic-list-completions)))
  1247. ;;;   (use-local-map shell-mode-map)
  1248. ;;;   (make-local-variable 'shell-directory-stack)
  1249. ;;;   (setq shell-directory-stack nil)
  1250. ;;;   (setq comint-input-sentinel 'shell-directory-tracker)
  1251. ;;;   (run-hooks 'shell-mode-hook))
  1252. ;;;
  1253. ;;;
  1254. ;;; Note that make-comint is different from make-shell in that it
  1255. ;;; doesn't have a default program argument. If you give make-shell
  1256. ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
  1257. ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
  1258. ;;; of NIL, it barfs. Adjust your code accordingly...
  1259. ;;;
  1260.  
  1261. ;;; Do the user's customisation...
  1262.  
  1263. (defvar comint-load-hook nil
  1264.   "This hook is run when comint is loaded in.
  1265. This is a good place to put keybindings.")
  1266.     
  1267. (run-hooks 'comint-load-hook)
  1268.  
  1269. ;;; Change log:
  1270. ;;; 9/12/89 
  1271. ;;;  - Souped up the filename expansion procedures.
  1272. ;;;    Doc strings are much clearer and more detailed.
  1273. ;;;    Fixed a bug where doing a filename completion when the point
  1274. ;;;    was in the middle of the filename instead of at the end would lose.
  1275. ;;;
  1276. ;;; 2/17/90 
  1277. ;;;  - Souped up the command history stuff so that text inserted
  1278. ;;;    by comint-previous-input-matching is removed by following
  1279. ;;;    command history recalls. comint-next/previous-input-matching
  1280. ;;;    is now much more smoothly integrated w/the command history stuff.
  1281. ;;;  - Added comint-eol-on-send flag and comint-input-sender hook.
  1282. ;;;    Comint-input-sender based on code contributed by Jeff Peck
  1283. ;;;    (peck@sun.com).
  1284. ;;;
  1285. ;;; 3/13/90 ccm@cmu.cs.edu
  1286. ;;;  - Added comint-previous-similar-input for looking up similar inputs.
  1287. ;;;  - Added comint-send-and-get-output to allow snarfing input from
  1288. ;;;    buffer. 
  1289. ;;;  - Added the ability to pick up a source file by positioning over
  1290. ;;;    a string in comint-get-source.
  1291. ;;;  - Added add-hook to make it a little easier for the user to use
  1292. ;;;    multiple hooks.
  1293. ;;;  
  1294. ;;; 5/22/90 shivers
  1295. ;;; - Moved Chris' multiplexed ipc stuff to comint-ipc.el.
  1296. ;;; - Altered Chris' comint-get-source string feature. The string
  1297. ;;;   is only offered as a default if it names an existing file.
  1298. ;;; - Changed comint-exec to directly crank up the process, instead
  1299. ;;;   of calling the env program. This made background.el happy.
  1300. ;;; - Added new buffer-local var comint-ptyp. The problem is that
  1301. ;;;   the signalling functions don't work as advertised. If you are
  1302. ;;;   communicating via pipes, the CURRENT-GROUP arg is supposed to
  1303. ;;;   be ignored, but, unfortunately it seems to be the case that you
  1304. ;;;   must pass a NIL for this arg in the pipe case. COMINT-PTYP
  1305. ;;;   is a flag that tells whether the process is communicating
  1306. ;;;   via pipes or a pty. The comint signalling functions use it
  1307. ;;;   to determine the necessary CURRENT-GROUP arg value. The bug
  1308. ;;;   has been reported to the Gnu folks.
  1309. ;;; - comint-dynamic-complete flushes the help window if you hit space
  1310. ;;;   after you execute it.
  1311. ;;; - Added functions comint-send-string, comint-send-region and var 
  1312. ;;;   comint-input-chunk-size.  comint-send-string tries to prevent processes
  1313. ;;;   from hanging when you send them long strings by breaking them into
  1314. ;;;   chunks and allowing process output between chunks. I got the idea from
  1315. ;;;   Eero Simoncelli's Common Lisp package. Note that using
  1316. ;;;   comint-send-string means that the process buffer's contents can change
  1317. ;;;   during a call!  If you depend on process output only happening between
  1318. ;;;   toplevel commands, this could be a problem. In such a case, use
  1319. ;;;   process-send-string instead. If this is a problem for people, I'd like
  1320. ;;;   to hear about it.
  1321. ;;; - Added comint-proc-query as a simple mechanism for commands that
  1322. ;;;   want to query an inferior process and display its response. For a
  1323. ;;;   typical use, see lisp-show-arglist in cmulisp.el.
  1324. ;;; - Added constant comint-version, which is now "2.01".
  1325. ;;;
  1326. ;;; 6/14/90 shivers
  1327. ;;; - Had comint-update-env defined twice. Removed extra copy. Also
  1328. ;;;   renamed mem to be comint-mem, for modularity. The duplication
  1329. ;;;   was reported by Michael Meissner.
  1330. ;;; 6/16/90 shivers
  1331. ;;; - Emacs has two different mechanisms for maintaining the process
  1332. ;;;   environment, determined at compile time by the MAINTAIN-ENVIRONMENT
  1333. ;;;   #define. One uses the process-environment global variable, and
  1334. ;;;   one uses a getenv/setenv interface. comint-exec assumed the
  1335. ;;;   process-environment interface; it has been generalised (with
  1336. ;;;   comint-exec-1) to handle both cases. Pretty bogus. We could,
  1337. ;;;   of course, skip all this and just use the etc/env program to
  1338. ;;;   handle the environment tweaking, but that obscures process
  1339. ;;;   queries that other modules (like background.el) depend on. etc/env
  1340. ;;;   is also fairly bogus. This bug, and some of the fix code was
  1341. ;;;   reported by Dan Pierson.
  1342. ;;;
  1343. ;;; 9/5/90 shivers
  1344. ;;; - Changed make-variable-buffer-local's to make-local-variable's.
  1345. ;;;   This leaves non-comint-mode buffers alone. Stephane Payrard
  1346. ;;;   reported the sloppy useage.
  1347. ;;; - You can now go from comint-previous-similar-input to
  1348. ;;;   comint-previous-input with no problem.
  1349. ;;;
  1350. ;;; 12/21/90 shivers
  1351. ;;; - Added a condition-case to comint-get-source. Bogus strings
  1352. ;;;   beginning with ~ were making the file-exists-p barf.
  1353. ;;; - Added "=" to the set of chars recognised by file completion
  1354. ;;;   as constituting a filename.
  1355. ;;;
  1356. ;;; 1/90 shivers
  1357. ;;; These changes comprise release 2.02:
  1358. ;;; - Removed the kill-all-local-variables in comint-mode. This
  1359. ;;;   made it impossible for client modes to set things before calling
  1360. ;;;   comint-mode. (In particular, it messed up ilisp.el) In general,
  1361. ;;;   the client mode should be responsible for a k-a-l-v's.
  1362. ;;; - Fixed comint-match-partial-pathname so that it works in
  1363. ;;;   more cases: if the filename begins at the start-of-buffer;
  1364. ;;;   if point is on the first char of the filename. Just a question
  1365. ;;;   of getting the tricky bits right.
  1366. ;;; - Added a hook, comint-exec-hook that is run each time a process
  1367. ;;;   is cranked up. Useful for things like process-kill-without-query.
  1368. ;;;
  1369. ;;; These two were pointed out by tale:
  1370. ;;; - Improved the doc string in comint-send-input a little bit.
  1371. ;;; - Tweaked make-comint to check process status with comint-check-proc
  1372. ;;;   instead of equivalent inline code. 
  1373. ;;;
  1374. ;;; - Prompt-search history commands have been commented out. I never
  1375. ;;;   liked them; I don't think anyone used them.
  1376. ;;; - Made comint-exec-hook a local var, as it should have been.
  1377. ;;;   (This way, for instance, you can have cmushell procs kill-w/o-query,
  1378. ;;;    but let Scheme procs be default.)
  1379. ;;;
  1380. ;;; 7/91 Shivers
  1381. ;;; - Souped up comint-read-noecho with an optional argument, STARS.
  1382. ;;;   Suggested by mjlx@EAGLE.CNSF.CORNELL.EDU.
  1383. ;;; - Moved comint-previous-input-matching from C-c r to C-M-r.
  1384. ;;;   C-c <letter> bindings are reserved for the user.
  1385. ;;;   These bindings were done by Jim Blandy.
  1386. ;;; These changes comprise version 2.03.
  1387.  
  1388.